package resemClass;

import java.sql.*;

public class ConfigMySQL {
    static final String DB_URL = "jdbc:mysql://localhost:3306/resemblance";
    static final String USER = "root";
    static final String PASS = "12345678c";
    static int cols = 0;

    public static boolean login(String user, String psd) throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT * FROM `user` WHERE username='" + user + "'and password='" + psd + "'";
            ResultSet rs = stmt.executeQuery(sql);
            if (rs.next()) {
                rs.close();
                stmt.close();
                conn.close();
                return true;
            } else {
                rs.close();
                stmt.close();
                conn.close();
                return false;
            }
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }// 什么都不做
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        return false;
    }


    public static double[][] getTable(String user) throws ClassNotFoundException, SQLException {
        double[][] res = new double[50][50];
        Connection conn = null;
        PreparedStatement sql = null;
        ResultSet rs = null;
        boolean table_exists = true;
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            sql = conn.prepareStatement("SELECT * FROM `" + user + "`");
            try{
                rs = sql.executeQuery();
            } catch (Exception x){
                System.out.println("找不到数据表");
                table_exists = false;
            }

            if (table_exists) {
                rs.last();
                cols = rs.getRow();
                rs.beforeFirst();
                int count = 0;
                while (rs.next()) {
                    for (int i = 0; i < cols; i++) {
                        res[count][i] = Double.parseDouble(rs.getString("Gl-" + (i + 1)));
                    }
                    count++;
                }
            }
            rs.close();
            conn.close();
        return res;
    }
}
